const app = getApp();

Page({
  data: {
    userInfo: null
  },

  onLoad() {
    this.setData({ userInfo: app.globalData.userInfo });
  },

  onShow() {
    this.setData({ userInfo: app.globalData.userInfo });
  },

  onMyPosts() {
    if (!this.checkLogin()) return;
    wx.navigateTo({ url: '/pages/user/posts/posts' });
  },

  onMyFavorites() {
    if (!this.checkLogin()) return;
    wx.navigateTo({ url: '/pages/user/favorites/favorites' });
  },

  onChatList() {
    if (!this.checkLogin()) return;
    wx.navigateTo({ url: '/pages/chat/list/list' });
  },

  onPaymentHistory() {
    if (!this.checkLogin()) return;
    wx.navigateTo({ url: '/pages/payment/history/history' });
  },

  onLogin() {
    wx.navigateTo({ url: '/pages/user/login/login' });
  },

  onLogout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          app.globalData.token = null;
          app.globalData.userInfo = null;
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          this.setData({ userInfo: null });
          wx.showToast({ title: '已退出登录', icon: 'success' });
        }
      }
    });
  },

  checkLogin() {
    if (!app.globalData.userInfo) {
      wx.navigateTo({ url: '/pages/user/login/login' });
      return false;
    }
    return true;
  }
});